//
//  ST_TicketViewController.swift
//  btvideo
//
//  Created by mac on 2020/9/23.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyUserDefaults
import Alamofire
import MBProgressHUD
import RxCocoa
import RxSwift
//import Rswift

enum ST_TicketFrom {
    /// 注册流程
    case register
    /// 来自主界面限制
    case mainIndexConfined
}


class ST_TicketViewController: UIViewController,ST_RegisterRouteProtocol {
    
    deinit{
        print(" ST_TicketViewController  deinit tag")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if from == .mainIndexConfined{
            ST_BTUserInfoManager.shared.ticket_controller = self
        }
        
        
        layout_u_i()
        
        binding()
        
        back_thread_execute(afterDelay: 1) {
            ST_RegisterMonitor.shared.logger.report(fromController: self)
        }
        
        check()
        NotificationCenter.default.addObserver(self, selector: #selector(check), name: Notification.Name.refreshTicketStatusWhenBackApp, object: nil)
    }
    
    @objc func check() {
        JVrequest(PH.BASE_URL + "vdsns/payOrderV73/getMemberRfq/v2.json") { json in
            if json["data"]["ticket_paid"].boolValue == true {
                self.nextPushHandle()
            }
        } failure: { code, err in
        }
    }
    
    var from = ST_TicketFrom.register
    
    
    
    fileprivate var data_array = [ST_ExampleTraitCellModel]()
    
    fileprivate lazy var sourceArray = [ST_ExampleTraitCellModel]()
    
    fileprivate var link:CADisplayLink?
    
    fileprivate lazy var ticket_title_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#333333")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate lazy var ticket_title_top_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#333333")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate lazy var right_box_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("编组22222"))
        return control
    }()
    
    
    fileprivate lazy var box_title_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#FEC207")
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var box_sub_title_label:UILabel = {
        
        let control = UILabel.init()
      
        control.textColor = UIColor(hexString: "#FEC207")
        
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var ticket_sub_title_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor(hexString: "#333333")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var confirm_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.init(hex: 0xFEC207)
        control.cornerRadius = 44/2.0
        //        control.borderColor = UIColor.init(hex: 0xDFE3E9)
        //        control.borderWidth = 1
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(confirm_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var gray_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.clear
        control.cornerRadius = 44/2.0
        control.borderColor = UIColor.init(hex: 0xDFE3E9)
        control.borderWidth = 1
        control.setTitleColor(UIColor.init(hex: 0xACB4C0), for: UIControl.State.normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.addTarget(self, action: #selector(grayHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var helper_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("支付帮助")
        control.borderColor = .white
        control.borderWidth = 1
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.setTitleColorForAllStates(UIColor.white)
        control.backgroundColor = .clear
        control.cornerRadius = 11
        control.add_touch_up(insideTarget: self, action: #selector(helper_handle))
        return control
    }()
    
    
    
    
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
        let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = ST_PinterestHomeCellMinimumColumnSpacing
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 10, bottom: 0, right: 10)
        return controlLayout
    }()
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
        let control = ST_FWGradientView()
        //        control.bgLayer.colors = [UIColor.init(white: 1, alpha: 0).cgColor,UIColor.init(white: 1, alpha: 1).cgColor]
        //        control.bgLayer.startPoint = CGPoint(x: 1, y: 0)
        //        control.bgLayer.endPoint = CGPoint(x: 1, y: 1)
        control.bgLayer.startPoint = CGPoint(x: 0.5, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0.5, y: 0.5)
        control.bgLayer.colors = [UIColor(red: 1, green: 1, blue: 1, alpha: 0).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor]
        return control
    }()
    
    fileprivate var incrementY = 0.cgFloat
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = UIColor.white
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        control.isScrollEnabled = false
        control.register(cellWithClass: ST_ExampleTraitCell.self)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    fileprivate lazy var subBoxView:UIView = {
        let control = UIView()
        control.backgroundColor = .clear
        control.cornerRadius = 15
        control.borderColor = UIColor.init(hex: 0xFEC207)
        control.borderWidth = 3
        return control
    }()
    
    fileprivate var product_identifier:String?
    
    fileprivate var city = ""
    
}



extension ST_TicketViewController{
    
    fileprivate func binding(){
        
        let city_observer:Observable<String>
        
        if from == .mainIndexConfined{
            city_observer = SCComponets.location_component.loc_pushed_observer.map { i -> String in
                
                if i == 1,let address = SCComponets.location_component.current_address{
                    return address.city
                }else{
                    return ""
                }
            }
        }else{
            city_observer = SCComponets.location_component.city_observer.compactMap({ $0 })
        }
        
        
        
        
        
        
        Observable.zip(city_observer,TIANSession(requestUrl: PH.payExampleListApi).wrap_response_data().retry(),TIANSession(requestUrl: PH.featureExampleListApi).wrap_response_data().retry()).withUnretained(self).subscribe { own,arg in
            
            
            var city = arg.0
            
            if city.count > 4{
                city = NSMutableString.init(string: city).substring(with: NSMakeRange(0, 4))
            }else if city == ""{
                city = "附近"
            }
            
            let jsonInfo = arg.1["data"]
            
            
            var title1 = jsonInfo["title1"].stringValue
            title1 = title1.replacingOccurrences(of: "[city]", with: city)
            own.ticket_title_top_label.text = title1
            
            
            
            var title2 = jsonInfo["title2"].stringValue
            title2 = title2.replacingOccurrences(of: "[total_num]", with: arg.1["data"]["total_num"].stringValue)
            own.ticket_title_label.text = title2
            
            own.ticket_sub_title_label.text = jsonInfo["title3"].stringValue
            own.box_title_label.text = jsonInfo["txt1"].stringValue
            
            
            let count = Defaults[.IncreasedMemberCount] + Int.random(in: 50...100)
            Defaults[.IncreasedMemberCount] = count
            
            var txt2 = jsonInfo["txt2"].stringValue
            txt2 = txt2.replacingOccurrences(of: "[join_num]", with: count.string)
            own.box_sub_title_label.text = txt2
            
            
            own.confirm_btn.setTitle(jsonInfo["btn1"].stringValue, for: .normal)
            own.gray_btn.setTitle(jsonInfo["btn2"].stringValue, for: .normal)
            
            own.product_identifier = arg.1["data"]["member"]["id"].stringValue
            
            
            
            
            
            
            if let list = [ST_ExampleTraitCellModel].deserialize(from: arg.2["data"].rawString() ?? "" ) as? [ST_ExampleTraitCellModel]{
                
                own.sourceArray = list
                
                own.sourceArray.forEach { (m) in
                    m.figure_out_param(city: city)
                }
            }
            
            own.data_array = own.sourceArray
            
            own.reload_with_start_link()
            
            
        }.disposed(by: rx.disposeBag)
        
        
    }
    
    
    fileprivate func reload_with_start_link(){
        
        collectionView.reloadData {
            
            self.link = CADisplayLink.init(target: self, selector: #selector(self.scrollAutomatically))
            
            self.link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
        }
        
        
    }
    
    fileprivate func linkInvalidate(){
        
        self.link?.invalidate()
        self.link = nil
        
    }
    
    
}

extension ST_TicketViewController{
    
    fileprivate func layout_u_i(){
        
        view.backgroundColor = UIColor.white
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom+200, right: 0))
        }
        
        view.addSubview(gradient_view)
        gradient_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom)
            make.height.equalTo(534)
        }
        
        view.addSubview(gray_btn)
        gray_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(44)
            make.width.equalTo(260)
            make.bottom.equalToSuperview().offset(-64-BTSafeAreaBottom)
        }
        
        
        view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(gray_btn)
            make.bottom.equalTo(gray_btn.snp.top).offset(-10)
        }
        
        
        view.addSubview(subBoxView)
        subBoxView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(79)
            make.bottom.equalTo(confirm_btn.snp.top).offset(-20)
        }
        
        subBoxView.addSubview(right_box_image_view)
        right_box_image_view.snp.makeConstraints { (make) in
            make.right.bottom.top.equalToSuperview()
            make.width.equalTo(118)
        }
        
        subBoxView.addSubview(box_title_label)
        box_title_label.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(15)
            make.height.equalTo(25)
        }
        
        subBoxView.addSubview(box_sub_title_label)
        box_sub_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(45)
            make.height.equalTo(17)
        }
        
        
        
        
        view.addSubview(ticket_sub_title_label)
        ticket_sub_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(22)
            make.bottom.equalTo(subBoxView.snp.top).offset(-20)
        }
        
        view.addSubview(ticket_title_label)
        ticket_title_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(26)
            make.bottom.equalTo(ticket_sub_title_label.snp.top).offset(-10)
        }
        
        view.addSubview(ticket_title_top_label)
        ticket_title_top_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(26)
            make.bottom.equalTo(ticket_title_label.snp.top)
        }
        
        //        view.addSubview(helper_btn)
        //        helper_btn.snp.makeConstraints { (make) in
        //            make.width.equalTo(64)
        //            make.height.equalTo(23)
        //            make.right.equalToSuperview().offset(-10)
        //            make.top.equalToSuperview().offset(16)
        //        }
    }
    
}


extension ST_TicketViewController{
    
    @objc fileprivate func helper_handle(){
        
        if Defaults[.isPanda]{
            
            
            guard let url = URL(string: PH.helpPayHtml.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) else { return  }
            
            let vc = ST_RegistStepHelperController()
            
            vc.url = url
            
            vc.hiddenfeedback = true
            
            GlobalPresent(toController: vc)
            
            
        }else{
            
            GlobalPresent(toController: UINavigationController.create_hiding_bar_navigation_controller(rootViewController: ST_DesignDAController()))
            
        }
        
    }
    
    @objc fileprivate func grayHandle(){
        
        ST_BTGlobalDataCenter.shared.whyPayForItEvent()
//
//        let vc = ST_TicketInfoController()
//
//        vc.overCurrentContext = true
//
//        GlobalPresent(toController: vc)
        
        let vc = ST_TicketTipViewController()
        vc.overCurrentContext = true
        GlobalPresent(toController: vc)
    }
    
    
    @objc fileprivate func confirm_handle(){
        
        guard let ename = product_identifier else { return  }
        
        ST_BTGlobalDataCenter.shared.payImmediatelyEvent()
        
        let manager = ST_MaidWayManager.shared
        
        manager.source = .认证会员
        
        manager.doWay(id: ename, delegate: self)
        
    }
    
    @objc fileprivate func nextPushHandle(){
        
        linkInvalidate()
        
        switch from {
        case .register:
            self.pushNextRegisterController(parameters: nil)
        case .mainIndexConfined:
            self.goback_previous_controller()
        }
        
    }
    
}

extension ST_TicketViewController:ST_TIANPaymentTransactionStateDelegate{
    
    func transaction_succeed() {
        
        nextPushHandle()
    }
    
}


extension ST_TicketViewController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        
        let m = data_array[indexPath.row]
        
        return CGSize.init(width: ST_PinterestHomeCellImageWidth, height: m.cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ExampleTraitCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        ST_BTGlobalDataCenter.shared.clickFinalRegisterEvent()
        
    }
    
    
    @objc func scrollAutomatically() {
        
        
        if self.data_array.count < 1{
            return
        }
        
        
        
        if collectionView.indexPathsForVisibleItems.contains(IndexPath.init(row: self.data_array.count-1, section: 0)){
            
            linkInvalidate()
            
            return
        }
        
        
        incrementY += 1.5/3.0
        
        collectionView.setContentOffset(CGPoint.init(x: 0, y: incrementY), animated: false)
        
        
    }
    
}

